import { toast } from '../../../../utils/expendApi'
import { setStorage } from '../../../../utils/storage'
import { userBehavior } from './behavior'
import { reqUploadFile, reqUpdateUserInfo } from '../../../../api/user'
Page({
  behaviors: [userBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    isShowPopup: false,
  },
  // 选取头像
  async chooseAvatar (e) {
    const { avatarUrl } = e.detail
    const {data} = await reqUploadFile( avatarUrl, 'file')
    // 先更新本地的信息 
    this.setData({
      'userInfo.headimgUrl': data
    })
  },
  // 显示获取用户昵称dialog
  onUpdateNickName () {
    this.setData({
      isShowPopup: true,
      'userInfo.nickname': this.data.userInfo.nickname,
    })
  },
  // 获取用户昵称
  getNickName (e) {
    const { nickname } = e.detail.value
    this.setData({
      'userInfo.nickname': nickname,
      isShowPopup: false
    })
  },
  // 弹框取消按钮
  cancelForm() {
    this.setData({
      isShowPopup: false
    })
  },
  // 保存更新仓库和本地数据
  async updateUser () {
    const res = await reqUpdateUserInfo(this.data.userInfo)
    if(res.code === 200) {
      // 本地更新
      setStorage('userInfo', this.data.userInfo)
      // 仓库更新
      this.setUserInfo(this.data.userInfo)
      toast({title:'信息更新成功'})
    }
  }
})